home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Resources / Chat & Communication / Digsby build 37 / digsby_setup.exe / lib / common / actions.pyo (.txt) < prev    next >
Python Compiled Bytecode  |  2008-10-13  |  9KB  |  245 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.5)
  3.  
  4. from __future__ import with_statement
  5. __author__ = 'dotSyntax'
  6. import util
  7. import util.data_importer as importer
  8. from util import baseclasses, do, curly, import_function, funcinfo
  9. from functools import partial
  10. from types import FunctionType as function
  11. from collections import defaultdict
  12. from util.observe import Observable, ObservableMeta
  13. import logging
  14. log = logging.getLogger('actions')
  15. import wx
  16. import sys
  17. import syck
  18. from wx import BitmapFromImage
  19. _actions_cached = None
  20. _actions_imported = False
  21.  
  22. def _actions():
  23.     global _actions_imported
  24.     if _actions_imported:
  25.         return _actions_cached
  26.     
  27.     skin = skin
  28.     import gui
  29.     
  30.     try:
  31.         actions = importer.yaml_import('actions', loadpath = [
  32.             skin.resourcedir()])
  33.     except ImportError:
  34.         actions = { }
  35.     finally:
  36.         _actions_imported = True
  37.  
  38.     add_actions(actions)
  39.     return _actions_cached
  40.  
  41.  
  42. def add_actions(actionsdict):
  43.     global _actions_cached
  44.     the_actions = _actions()
  45.     if the_actions is None:
  46.         the_actions = { }
  47.     
  48.     the_actions = util.merge.merge(the_actions, actionsdict)
  49.     _actions_cached = the_actions
  50.  
  51.  
  52. def forclass(cls, search_bases = True):
  53.     if not isinstance(cls, type) and hasattr(cls, '__class__'):
  54.         cls = cls.__class__
  55.     
  56.     if search_bases:
  57.         classes = [
  58.             cls] + baseclasses(cls)
  59.         classes.reverse()
  60.     else:
  61.         classes = [
  62.             cls]
  63.     return util.flatten((lambda .0: for c in .0:
  64. _actions().get(c.__name__, []))(classes))
  65.  
  66.  
  67. class Action(Observable):
  68.     
  69.     def __init__(self, name, callable):
  70.         Observable.__init__(self)
  71.         util.autoassign(self, locals())
  72.  
  73.     
  74.     def __call__(self, *args, **kws):
  75.         return self.callable(*args, **kws)
  76.  
  77.     
  78.     def __repr__(self):
  79.         return '<Action %s for %r>' % (self.name, self.callable)
  80.  
  81.  
  82.  
  83. def menu(parent, obj, menu = None, cls = None, search_bases = True, filter = (lambda func: True)):
  84.     skin = skin
  85.     import gui
  86.     UMenu = UMenu
  87.     import gui.uberwidgets.umenu
  88.     actions = None(forclass if cls is not None else obj, search_bases)
  89.     menu = None if menu is not None else UMenu(parent)
  90.     names = set()
  91.     for action in actions:
  92.         if isinstance(action, basestring) and action.startswith('--'):
  93.             menu.AddSep()
  94.             continue
  95.         elif 'method' in action:
  96.             import_function(action['method'])(menu, obj)
  97.             continue
  98.         
  99.         name = action['call']
  100.         if name in names:
  101.             continue
  102.         else:
  103.             names.add(name)
  104.         func = getattr(obj, name, None)
  105.         if func is None:
  106.             continue
  107.         
  108.         bitmap = None if 'bitmap' in action else None
  109.         gui_name = action['name']
  110.         
  111.         try:
  112.             (precondition, needslist) = getattr(obj, '_actions')[name]
  113.         except KeyError:
  114.             e = None
  115.             
  116.             precondition = lambda v: True
  117.             needslist = []
  118.  
  119.         if needslist:
  120.             import gui.userform as userform
  121.             callback = partial(userform.getinput, obj, parent, needslist, func, title = gui_name.replace('&', ''))
  122.         elif 'gui' in action:
  123.             gui = import_function(action['gui'])
  124.             if not hasattr(gui, 'Prompt'):
  125.                 
  126.                 callback = lambda gui = gui, func = (func,): gui(obj, func)
  127.             else:
  128.                 
  129.                 def callback(gui = gui, func = (func,)):
  130.                     gui(None, obj).Prompt(func)
  131.  
  132.         else:
  133.             callback = func
  134.         result = None if precondition is not None else True
  135.         if filter(func):
  136.             if precondition is None or result is not None:
  137.                 name = action_name(obj, gui_name)
  138.                 menu.AddItem(name, bitmap = bitmap, callback = callback).Enable(bool(result))
  139.                 continue
  140.     
  141.     if menu.GetMenuItemCount() == 0:
  142.         menu.AddItem(_('No actions')).Enable(False)
  143.     
  144.     while menu[-1].IsSeparator():
  145.         menu.RemoveItem(menu[len(menu) - 1])
  146.     return menu
  147.  
  148.  
  149. def action_name(obj, name):
  150.     if name.find('$') != -1:
  151.         name = curly(name, source = {
  152.             'obj': obj })
  153.     
  154.     return name
  155.  
  156. _actioncalls = dict()
  157.  
  158. class ActionMeta(type):
  159.     action_prefix = '__ACTION__'
  160.     class_action_attr = '_actions'
  161.     
  162.     def __init__(cls, name, bases, dict):
  163.         super(ActionMeta, cls).__init__(name, bases, dict)
  164.         superactions = util.odict()
  165.         if 'inherited_actions' in dict:
  166.             bases = bases + tuple(dict['inherited_actions'])
  167.         
  168.         (do,)((lambda .0: for c in .0:
  169. if hasattr(c, '_actions'):
  170. superactions.update(c._actions)continue)(bases))
  171.         setattr(cls, ActionMeta.class_action_attr, superactions)
  172.         actions = getattr(cls, ActionMeta.class_action_attr)
  173.         prefix = ActionMeta.action_prefix
  174.         for v in dict.itervalues():
  175.             if isinstance(v, function) and v.__name__.startswith(prefix):
  176.                 v.__name__ = v.__name__[len(prefix):]
  177.                 val = _actioncalls.pop(v)
  178.                 actions[v.__name__] = val
  179.                 continue
  180.         
  181.  
  182.  
  183.  
  184. class ActionType(object):
  185.     __metaclass__ = ActionMeta
  186.  
  187.  
  188. class ObservableActionMeta(ObservableMeta, ActionMeta):
  189.     pass
  190.  
  191.  
  192. class ActionError(Exception):
  193.     pass
  194.  
  195.  
  196. def _action_err_info(callable_predicate):
  197.     code = callable_predicate.func_code
  198.     fn = code.co_filename
  199.     ln = code.co_firstlineno
  200.     getline = getline
  201.     import linecache
  202.     if not getline(fn, ln):
  203.         pass
  204.     line = '<UNKNOWN>'
  205.     return (fn, ln, line)
  206.  
  207.  
  208. def action(callable_predicate = None, needs = None):
  209.     if callable_predicate is not None and not callable(callable_predicate):
  210.         raise TypeError("action decorator needs a callable or None as it's only argument (you gave a %s)" % type(callable_predicate))
  211.     
  212.     
  213.     def action_dec(meth):
  214.         
  215.         def func(*args, **kws):
  216.             if callable_predicate:
  217.                 (filename, line, line_text) = _action_err_info(callable_predicate)
  218.                 err_msg = '%s is not allowed, %%s\nFile "%s", line %d, in %s\n%s' % (meth.__name__, filename, line, callable_predicate.__name__, line_text)
  219.                 
  220.                 try:
  221.                     allow = callable_predicate(*args, **kws)
  222.                 except TypeError:
  223.                     e = None
  224.                     raise ActionError, err_msg % 'error in precondition function: ' + str(e)
  225.  
  226.                 if not allow:
  227.                     log.warning(str(ActionError(err_msg % 'precondition not met for')))
  228.                 
  229.             
  230.             return meth(*args, **kws)
  231.  
  232.         func.__name__ = ActionMeta.action_prefix + meth.__name__
  233.         func.__doc__ = meth.__doc__
  234.         if callable_predicate:
  235.             func.action_allowed = callable_predicate
  236.         else:
  237.             
  238.             func.action_allowed = lambda *a, **k: True
  239.         tneeds = needs
  240.         _actioncalls[func] = (callable_predicate, tneeds)
  241.         return func
  242.  
  243.     return action_dec
  244.  
  245.